<?php

include './functions.php';

$data = $_POST;

if(strtolower($data['code'])!=$_SESSION['code']){
	exit(json_encode(['error'=>1,'msg'=>'验证码不正确']));
}

if($data['password']!=$data['repassword']){
	exit(json_encode(['error'=>1,'msg'=>'两次密码不一致']));
}

// 验证手机
// 验证邮箱
// 验证用户名

$preg = "/^[a-z][a-z\d]{5,7}$/";

$c = preg_match($preg,$data['username']);

if(!$c){
	exit(json_encode(['error'=>1,'msg'=>'用户由6-8位组成，第一位不能是字母']));
}

$oldData = file_get_contents('./data/user.txt');
// 把json数据转成数组 
$oldData = json_decode($oldData,true);

// 判断用户是否存在
foreach ($oldData as  $v) {
	if($v['username']==$data['username']){
		exit(json_encode(['error'=>1,'msg'=>'用户名已存在']));
	}
}

$data['ctime'] = time();

$data['password'] = md5($data['password']);

unset($data['repassword']);
unset($data['code']);

$oldData[] = $data;
//转json格式
$oldData = json_encode($oldData);
// 写到数据库文件
file_put_contents('./data/user.txt',$oldData);

exit(json_encode(['error'=>0,'msg'=>'注册成功']));